import { _decorator, Component, Sprite, SpriteFrame, input, Input, KeyCode, EventKeyboard } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('MoveControl')
export class MoveAndSwitchSprite extends Component {
    @property([SpriteFrame]) 
    spriteFrames: SpriteFrame[] = [];

    @property
    moveSpeed: number = 300; 

    private sprite: Sprite | null = null; 

    start() {
        this.sprite = this.getComponent(Sprite);  

        var i = 0; 

        this.updateSprite(i);
    
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
    }

   

    onKeyDown(event: EventKeyboard) {
        if (!this.sprite) return;

        switch (event.keyCode) {
            case KeyCode.ARROW_UP: 
            case KeyCode.KEY_W: // 上
                this.updateSprite(0);
                this.node.position = this.node.position.add3f(0, this.moveSpeed, 0);
                break;
            case KeyCode.ARROW_DOWN:
            case KeyCode.KEY_S:  // 下
                this.updateSprite(1); 
                this.node.position = this.node.position.add3f(0, -this.moveSpeed, 0);
                break;
            case KeyCode.ARROW_LEFT:
            case KeyCode.KEY_A:  // 左
                this.updateSprite(2); 
                this.node.position = this.node.position.add3f(-this.moveSpeed, 0, 0);
                break;
            case KeyCode.ARROW_RIGHT:
            case KeyCode.KEY_D:  // 右
                this.updateSprite(3); 
                this.node.position = this.node.position.add3f(this.moveSpeed, 0, 0);
                break;
        }
    }

    onKeyUp(event: EventKeyboard) {
        console.log(`pressed: ${event.keyCode}`);
    }

    updateSprite(index: number) {
        if (this.sprite && this.spriteFrames[index]) {
            this.sprite.spriteFrame = this.spriteFrames[index];
        }
    }
}
